package com.hinotoyk.testsystem.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @program: testsystem
 * @description:
 * @author: DYJ
 * @create: 2019-11-18 22:28
 **/
//验证码生成控制器
@Controller
public class KaptchaController {

    @Resource
    DefaultKaptcha defaultKaptcha;

    @RequestMapping("/createVSCode")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        byte[] captchaToJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        
        try{
            String rightCode = defaultKaptcha.createText();
            request.getSession().setAttribute("rightCode",rightCode);
            BufferedImage image = defaultKaptcha.createImage(rightCode);
            ImageIO.write(image, "jpg", jpegOutputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaToJpeg = jpegOutputStream.toByteArray();
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaToJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @RequestMapping("/verifyVSCode")
    @ResponseBody
    public String verifyVSCode(@RequestBody String tryCode, HttpServletRequest request){
        String rightCode = (String) request.getSession().getAttribute("rightCode");
        System.out.println(tryCode);
        String[] str= tryCode.trim().split("=");
        if(str.length <=1){
            return "false";
        }
        if(!rightCode.equals(str[1])){
            return "false";
        }
        return "true";
    }


}
    